package com.math.aistudykbr.mapper;

import com.math.aistudykbr.pojo.entity.ChoiceQuestion;
import com.math.aistudykbr.pojo.entity.LearningMaterial;
import com.math.aistudykbr.pojo.entity.UserAnswer;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface QAMapper {

    // ====== 学习资料相关 ======
    @Select("SELECT * FROM learning_materials WHERE id = #{id}")
    LearningMaterial getMaterialById(Long id);

    // 查询材料ID
    @Select("SELECT id FROM learning_materials WHERE user_id = #{userId} AND status = 1 AND title = #{title}")
    Long getMaterialIdByTitleAndUserId(Long userId, String title);

    @Insert("INSERT INTO learning_materials (title, content, file_path, file_type, user_id, status) " +
            "VALUES (#{title}, #{content}, #{filePath}, #{fileType}, #{userId}, #{status})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void saveMaterial(LearningMaterial material);

    // ====== 选择题相关 ======
    @Insert("INSERT INTO choice_questions (material_id, question_content, option_a, option_b, option_c, option_d, " +
            "correct_answer, explanation, difficulty_level) " +
            "VALUES (#{materialId}, #{questionContent}, #{optionA}, #{optionB}, #{optionC}, #{optionD}, " +
            "#{correctAnswer}, #{explanation}, #{difficultyLevel})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void saveQuestion(ChoiceQuestion question);

    @Select("SELECT * FROM choice_questions WHERE material_id = #{materialId}")
    List<ChoiceQuestion> getQuestionsByMaterial(Long materialId);

//    @Select("SELECT * FROM choice_questions WHERE id = #{id}")
//    ChoiceQuestion getQuestionById(Long id);

    // ====== 用户答题相关 ======
//    @Insert("INSERT INTO user_answers (user_id, question_id, user_answer, is_correct) " +
//            "VALUES (#{userId}, #{questionId}, #{userAnswer}, #{isCorrect})")
//    @Options(useGeneratedKeys = true, keyProperty = "id")
//    void saveUserAnswer(UserAnswer answer);

    @Delete("DELETE lm, cq FROM learning_materials lm " +
            "LEFT JOIN choice_questions cq ON cq.material_id = lm.id " +
            "WHERE lm.user_id = #{userId}")
    void deleteUserAllData(Long userId);

    @Update("UPDATE choice_questions SET userAnswer = #{userAnswer}, is_correct = #{isCorrect} " +
            "WHERE material_id = #{materialId} AND id = #{questionId}")
    void updateQuestionAnswer(Long materialId, Long questionId, String userAnswer, int isCorrect);
}
